package com.ltu.m7011e.imagine.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HasHTML;
import com.google.gwt.user.client.ui.ListenerWrapper;
import com.google.gwt.user.client.ui.SourcesClickEvents;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.impl.HyperlinkImpl;

@SuppressWarnings("deprecation")
public class MenuLink extends Widget implements HasHTML, SourcesClickEvents, HasClickHandlers
{
	private static HyperlinkImpl impl = GWT.create(HyperlinkImpl.class);
	
	private static Element elemNull = null;
	private final Element anchorElem = DOM.createAnchor();
	private String targetHistoryToken;
	
	public MenuLink()
	{
		this(elemNull);
	}
	
	public MenuLink(String text)
	{
		this(text, text);
	}
	
	public MenuLink(String text, String targetHistoryToken)
	{
		this(elemNull);
		setText(text);
		setTargetHistoryToken(targetHistoryToken);
	}

	protected MenuLink(Element elem)
	{
		if(elem == null)
		{
			setElement(anchorElem);
		}
		else
		{
			setElement(elem);
			DOM.appendChild(getElement(), anchorElem);
		}
		
		sinkEvents(Event.ONCLICK);
		//setStyleName("gwt-Hyperlink");
	}


	@Override
	public String getHTML()
	{
		return DOM.getInnerHTML(anchorElem);
	}

	@Override
	public void setHTML(String html)
	{
		DOM.setInnerHTML(anchorElem, html);
	}

	public String getTargetHistoryToken()
	{
		return targetHistoryToken;
	}

	public void setTargetHistoryToken(String targetHistoryToken)
	{
		this.targetHistoryToken = targetHistoryToken;
		DOM.setElementProperty(anchorElem, "href", "#" + targetHistoryToken);
	}
	
	@Override
	public String getText()
	{
		return DOM.getInnerText(anchorElem);
	}

	@Override
	public void setText(String text)
	{
		DOM.setInnerText(anchorElem, text);
	}
	
	public void onBrowserEvent(Event event)
	{
		super.onBrowserEvent(event);
		if(DOM.eventGetType(event) == Event.ONCLICK && impl.handleAsClick(event))
		{
			History.newItem(getTargetHistoryToken(), true);
			DOM.eventPreventDefault(event);
		}
	}

	public HandlerRegistration addClickHandler(ClickHandler handler)
	{
		return addHandler(handler, ClickEvent.getType());
	}

	@Deprecated
	public void addClickListener(ClickListener listener)
	{
		ListenerWrapper.WrappedClickListener.add(this, listener);
	}

	@Deprecated
	public void removeClickListener(ClickListener listener)
	{
		ListenerWrapper.WrappedClickListener.remove(this, listener);
	}
}
